<template>
  <div class="v-html-textarea">
    <div>
      <div class="v-editor-textarea">
        <el-input
          v-if="selected"
          v-model="text"
          type="textarea"
          :style="{ height: editDivHeight }"
          maxLength="20"
          :disabled="row.readonly || isModelDisabled"
          :inputStyle="{ minHeight: '24px' }"
          @change="handelChange"
        />
        <div
          v-if="!selected"
          ref="showDiv"
          class="g-pd-lr-7"
        >
          <span v-if="containTermName.length">
            <span
              v-for="(item, index) in containTermName"
              :key="index"
            >
              <span
                v-if="item.isTerm"
                class="show-underline"
                @contextmenu.stop="event => showDetailTerm(event, item.name)"
              >
                {{ item.name }}
              </span>
              <span v-else>{{ item.name }}</span>
            </span>
          </span>
          <span v-else>{{ text }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, Ref, inject, computed } from "vue";
import { BusEvent, PropertyKey } from "@/constants/Enums";
import { modelService } from "@/modules/model/service";
import { PropertyRow } from "../../types";
import { ContainTermName, splitOriginTextWithTerms } from "@/mdesign-lib/mdesign-graph.umd.js";
import { showDetailTermCommon } from "@/modules/model/service/termBankService";
import { ModelData } from "@/constants/types";

const isModelDisabled = inject("isModelDisabled") as Ref<boolean>;
const props = defineProps<{
  row: PropertyRow;
  selected?: boolean;
  editDivHeight?: number;
}>();

const text = ref(props.row.value as string);
let showDiv = ref<HTMLElement>();
let editDivHeight = ref(props.editDivHeight ? Math.max(props.editDivHeight, 24) + "px" : "24px");

let parentId = "";
let applyToElements: string[] = [];
let isNameUni = false;
let prefixRule = "";
let separator = "";
let prefix = "";

// 获取最新属性
async function getParamDefaultValue() {
  const list = await modelService.getModelProperties(app.activeProjectId, props.row.modelId);
  let ownerValue = list.find(item => item.key === PropertyKey.Element_owner)?.value as ModelData;
  parentId = ownerValue.id;

  list.forEach(item => {
    switch (item.key) {
      case PropertyKey.Customization_NamingRule_applyToElements:
        {
          let applyToElementsValue = item.value as ModelData[];
          applyToElements = applyToElementsValue.map(it => it.id) || [];
        }
        break;

      case PropertyKey.Customization_NamingRule_isNameUni:
        isNameUni = item.value as boolean;
        break;

      case PropertyKey.Customization_NamingRule_prefixRule:
        {
          let prefixRuleValue = item.value as ModelData;
          prefixRule = prefixRuleValue ? prefixRuleValue.id : "";
        }
        break;

      case PropertyKey.Customization_NamingRule_separator:
        separator = item.value as string;
        break;

      case PropertyKey.Customization_NamingRule_prefix:
        prefix = item.value as string;
        break;

      default:
        break;
    }
  });
}

watch(
  () => props.row.value,
  newVal => (text.value = newVal as string)
);
watch(
  () => props.selected,
  newVal => {
    // 从非编辑状态进入编辑状态，将显示时候的高度复制给编辑状态的div
    if (newVal && showDiv.value) {
      const height = Math.max(showDiv.value.clientHeight, 24) + "px";
      editDivHeight.value = height;
    }
  }
);

const handelChange = async () => {
  await getParamDefaultValue();

  const res = await modelService.batchUpdateNamingRule({
    projectId: app.activeProjectId,
    parentId,
    namingRules: [
      {
        dataType: "update",
        nameRuleId: props.row.modelId,
        applyToElements,
        isNameUni,
        defaultName: text.value,
        prefixRule,
        separator,
        prefix
      }
    ]
  });

  if (res) {
    app.$bus.emit(BusEvent.REFRESH_PROPERTY, props.row.modelId);
  }
};

const containTermName = computed(() => {
  let _containTermName: ContainTermName[] = [];
  _containTermName = splitOriginTextWithTerms((props.row.value as string) || "", props.row.terms || []);
  return _containTermName;
});

function showDetailTerm(event: MouseEvent, termText: string) {
  if (props.row.readonly || isModelDisabled?.value) return;
  showDetailTermCommon(event, termText);
}
</script>

<style lang="scss" scoped>
.v-html-textarea {
  display: flex;
  .v-editor-textarea {
    flex: 1 1 100px;
    .el-textarea__inner {
      height: 100%;
      font-size: 11px;
      line-height: 24px;
      resize: none;
      padding: 0 7px;
      &:hover {
        box-shadow: none;
      }
    }
  }
  > .img-btn {
    display: flex;
    align-items: center;
    flex: 0 0 auto;
    width: 29px;
    padding-left: 5px;
  }
}
</style>
